import Mock from 'mockjs'

// get请求从config.url获取参数，post从config.body中获取参数
function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}
/* 用户列表 */
let userList = []
const count = 100
for (let i = 0; i < count; i++) {
  userList.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      sex: Mock.Random.integer(0, 1),
      birth: Mock.Random.date(),
      phone: /^1[34578]\d{9}$/, //随机电话号码
      email: Mock.Random.email('qq.com'),
      addr: Mock.mock('@county(true)'),
      // addr: mockz.address(),
    })
  )
}

export default {
  /**
   *获取用户列表
   *需要携带参数 name,page,limt(分页大小)
   * @param name,page,limit
   * @return {{code:number,count:number,data:*[]}}
   **/
  getUser: (config) => {
    const { name, page = 1, pagesize = 20 } = param2Obj(config.url)
    const mockList = userList.filter((user) => {
      if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false
      return true
    })
    const pageList = mockList.filter((item, index) => index < pagesize * page && index >= pagesize * (page - 1))

    return {
      code: 200,
      count: mockList.length,
      data: pageList,
      message: '获取用户列表成功',
    }
  },
  /* 
获取所有用户的省份
*/
  getProvince: (config) => {
    return {
      code: 200,
      data: userList,
      message: '获取所有用户成功',
    }
  },
  /**
   * 增加用户
   * @param name, addr, age, birth, sex
   * @return {{code: number, data: {message: string}}}
   */
  addUser: (config) => {
    const { name, sex, birth, phone, email, addr } = JSON.parse(config.body)
    console.log(addr, 'addr')
    userList.unshift({
      id: Mock.Random.guid(),
      name: name,
      sex: sex,
      birth: birth,
      phone: phone,
      email: email,
      addr: addr,
    })
    return {
      code: 201,
      data: {
        message: '添加成功',
      },
    }
  },
  /**
   * 删除用户
   * @param id
   * @return {*}
   */
  deleteUser: (config) => {
    const id = config.body
    if (!id) {
      return {
        code: 400,
        message: '参数不正确',
      }
    } else {
      userList = userList.filter((u) => u.id !== id)
      return {
        code: 200,
        message: '删除成功',
      }
    }
  },
  /**
   * 修改用户
   * @param id, name, addr, age, birth, sex
   * @return {{code: number, data: {message: string}}}
   */
  editUser: (config) => {
    const { id, name, sex, birth, phone, email, addr } = JSON.parse(config.body)
    const sex_num = parseInt(sex)
    userList.some((u) => {
      if (u.id === id) {
        ;(u.name = name), (u.sex = sex_num), (u.birth = birth), (u.phone = phone), (u.email = email), (u.addr = addr)
        return true
      }
    })
    return {
      code: 201,
      data: {
        message: '修改成功',
      },
    }
  },
}
